package com.hanserwei.mapper;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;

public class MyBatisUtils {
    private static volatile SqlSessionFactory sqlSessionFactory;

    /**
     * 获取SqlSession实例
     * @return SqlSession实例
     */
    public static SqlSession getSqlSession() {
        // 使用双重检查锁定确保线程安全
        if (sqlSessionFactory == null) {
            synchronized (MyBatisUtils.class) {
                if (sqlSessionFactory == null) {
                    String resource = "mybatis-config.xml";
                    try (Reader reader = Resources.getResourceAsReader(resource)) {
                        sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
                    } catch (IOException e) {
                        throw new RuntimeException("Failed to load MyBatis configuration file: " + resource, e);
                    }
                }
            }
        }
        // 返回自动提交事务的SqlSession
        return sqlSessionFactory.openSession(true);
    }
}
